<?php

declare(strict_types=1);
/**
 * 创建人 : Forpastime
 *
 * @link     http://hypercmf.com
 * @document https://hyperf.wiki
 * @contact  forpastime@qq.com
 * @git  https://gitee.com/hypercmf/hypercmf1.0.git
 */
namespace App\Controller\Api;

use App\Annotation\AdminNode;
use App\Middleware\Auth\TokenBucketMiddleware;
use App\Service\AdminService;
use App\Service\UserServiceInterface;
use App\Service\WechatService;
use App\Utils\Result;
use EasyWeChat\Factory;
use EasyWeChat\Kernel\Messages\Transfer;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\GetMapping;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\Middlewares;
use Hyperf\HttpServer\Annotation\RequestMapping;
use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\Redis\Redis;
use Hyperf\Utils\ApplicationContext;

/**
 * @Middlewares({
 *     @Middleware(TokenBucketMiddleware::class)
 * })
 * @Controller(prefix="api/user")
 * Class UserController 已登录用户操作
 */
class UserController
{
    /**
     * @Inject()
     * @var RequestInterface
     */
    protected $request;

    /**
     * @Inject
     * @var UserServiceInterface
     */
    protected $userService;

    /**
     * @RequestMapping(path="wechat/login", methods={"get", "post"})
     */
    public function wechatLogin(RequestInterface $request)
    {
        $header = $request->getHeaders();
        $params = $request->all();
        $wechat = new WechatService($header['client-type'][0],[]);
        $res = $wechat->login($params['code'],$params);
        if($res['code']==0){
            return Result::error('微信登陆失败');
        }

        $user = $this->userService->login($header['client-type'][0],$res['data']);
        if(!empty($user['data'])){
            //登陆成功后保存token到redis
            $token = for_generate_user_token();

            $container = ApplicationContext::getContainer();
            $redis = $container->get(Redis::class);
            $redis->setex('HyperCMF:userToken:'.$user['data']['openid'], $token['expireTime'], $token['token']);
            $data = $res['data'];
            $data['openid']=$user['data']['openid'];
            $data['token']=$token['token'];
            return Result::success($data);

        }else{
            return Result::error('登陆失败');

        }
    }

    /**
     * 微信公众号服务端信息
     * @RequestMapping(path="wechat/server/event",methods={"get","post"})
     */
    public function serverEvent(WechatService $wechatService)
    {
        $param = $this->request->all();

        if(isset($param['echostr'])){
            //配置验证
            $res = $wechatService->checkToken();
            if(intval($res) == 200){
                return $param['echostr'];
            }else{
                var_dump($res);
            }
        }
        if(isset($param['MsgType'])){
            //判断是登陆，查询有用户信息直接返回
            if(isset($param['EventKey']) && (strpos($param['EventKey'],'login_') !== false)){
                if(isset($param['openid'])&&!empty($param['openid'])){
                    $where[] = ['official_openid','=',$param['openid']];
                    $userinfo = $this->userService->userInfo($where);
                }else if(isset($param['unionid'])&&!empty($param['unionid'])){
                    $where[] = ['unionid','=',$param['unionid']];
                    $userinfo = $this->userService->userInfo($where);
                }
                if($userinfo){
                    var_dump('database userinfo:');
                    $userinfo['openid'] = $param['openid'];
                    $redis = ApplicationContext::getContainer()->get(Redis::class);
                    $redis->setex("qrscene_".$param['EventKey'],3600,json_encode($userinfo));
                    $wechatService->sendSuccessMsg($param,'登陆成功');
                    return "SUCCESS";
                }
            }
            $res = $wechatService->event($param);
            if($res->getStatusCode()==200){
                return "SUCCESS";
            }else{
                return "异常";
            }
        }

    }



    /**
     * 获取微信公众号临时二维码
     * @GetMapping(path="wechat/qrcode")
     * @param WechatService $wechatService
     * @return array
     */
    public function getSceneQrcode(WechatService $wechatService)
    {
        $scene = 'login_'.time().mt_rand(100,990);
        $res = $wechatService->getQrcode($scene);
        $res['scene'] = $scene;
        return Result::success($res);
    }

    /**
     * 检查是否扫码进入公众号
     * @GetMapping(path="wechat/checkScan")
     */
    public function checkScanQrcode(WechatService $wechatService)
    {
        $scene = $this->request->query('scene');
        $container = ApplicationContext::getContainer();
        $redis = $container->get(Redis::class);
        //$userinfo = $wechatService->getUserByQrscene($scene);
        $userinfo = $redis->get('qrscene_'.$scene);

        if($userinfo){
            $userinfo = json_decode($userinfo,true);

            //关注后获取了用户信息
            $user = $this->userService->login('pc',$userinfo);
            if(!empty($user['data'])){
                //登陆成功后保存token到redis
                $token = for_generate_user_token();

                $redis->setex('HyperCMF:userToken:'.$user['data']['openid'], $token['expireTime'], $token['token']);
                $data = [];
                if(empty($user['nick_name'])){
                    $data['nick_name'] = substr($user['data']['openid'],0,10);
                }
                $data['openid']=$user['data']['openid'];
                $data['token']=$token['token'];
                return Result::success($data);

            }else{
                return Result::error('登陆失败');

            }
            return Result::success($data);
        }else{
            return Result::error('未登录');
        }
    }
    /**
     * @RequestMapping(path="/mobile/login",methods={"get","post"})
     */
    public function mobileLogin()
    {

    }

    /**
     * @GetMapping(path="/bind/mobile")
     */
    public function bindMobile()
    {

    }
    /**
     * @GetMapping(path="info")
     */
    public function userInfo(RequestInterface $request)
    {

        var_dump($this->request->getHeaders('user-agent'));
        $id = $request->input('id', 0);
        if (empty($id)) {
            return Result::error('id为空');
        }
        $where[] = ['id','=',$id];
        $res = $this->userService->userInfo($where);
        return Result::success($res);
    }

    /**
     * @GetMapping(path="articles")
     */
    public function userArticles()
    {
        $res = $this->userService->userArticles();
        return Result::success($res);
    }

    /**
     * 用户列表
     * @GetMapping(path="userlist")
     */
    public function userList()
    {
        $res = $this->userService->users();
        return Result::success($res);
    }
}
